package current_subject

import current_scope "app/app_src/framework/security/current/scope"

type Subject struct {
	// 用户ID
	UserId int
	// 用户类型
	UserType string
	// 用户名
	UserName string
	// 权限
	Privileges []string
	// 租户ID
	TenantId int
}

const _CURRENT_SUBJECT_DATA_KEY = "security.current.subject"

func InitCurrentSubject(subject *Subject) {
	current_scope.Set(_CURRENT_SUBJECT_DATA_KEY, subject)
}

// 获取用户
func GetSubject() *Subject {
	data := current_scope.Get(_CURRENT_SUBJECT_DATA_KEY)
	if data == nil {
		return nil
	}

	subject, ok := data.(*Subject)
	if !ok {
		panic("current_scope.Get result type is not *Subject")
	}

	return subject
}

// 获取用户ID
func GetUserId() int {
	subject := GetSubject()

	if subject == nil {
		return -1
	}

	return subject.UserId
}

// 获取用户类型
func GetUserType() string {
	subject := GetSubject()

	if subject == nil {
		return ""
	}

	return subject.UserType
}

// 获取用户名
func GetUserName() string {
	subject := GetSubject()

	if subject == nil {
		return ""
	}

	return subject.UserName
}

// 获取权限
func GetPrivileges() []string {
	subject := GetSubject()

	if subject == nil {
		return []string{}
	}

	return subject.Privileges
}

// 获取租户ID
func GetTenantId() int {
	subject := GetSubject()

	if subject == nil {
		return -1
	}

	return subject.TenantId
}

// 获取用户
func MustGetSubject() *Subject {
	subject := GetSubject()

	if subject == nil {
		panic("GetSubject() nil")
	}

	return subject
}

// 获取用户ID
func MustGetUserId() int {
	subject := MustGetSubject()

	return subject.UserId
}

// 获取用户类型
func MustGetUserType() string {
	subject := MustGetSubject()

	return subject.UserType
}

// 获取用户名称
func MustGetUserName() string {
	subject := MustGetSubject()

	return subject.UserName
}

// 获取权限
func MustGetPrivileges() []string {
	subject := MustGetSubject()

	return subject.Privileges
}

// 获取租户ID
func MustGetTenantId() int {
	subject := MustGetSubject()

	return subject.TenantId
}
